package org.jansansad.client;

import java.util.List;
import java.util.SortedSet;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Jansansad implements EntryPoint {
	/**
	 * Create a remote service proxy to talk to the server-side Greeting service.
	 */
	private final GreetingServiceAsync greetingService = GWT
			.create(GreetingService.class);

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		final Label errorLabel = new Label();

		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		RootPanel.get("errorLabelContainer").add(errorLabel);
		
		final ListBox state = new ListBox();
		RootPanel.get("stateContainer").add(state);
		
		final ListBox constituency = new ListBox();
		RootPanel.get("constituencyContainer").add(constituency);
		NodeList<Element> nodeList = RootPanel.getBodyElement().getElementsByTagName("span");
		for (int i = 0; i < nodeList.getLength(); i++) {
			if (nodeList.getItem(i).getClassName().equals("billName")) {
				nodeList.getItem(i).setInnerText("Jan Lokpal Bill");
			}
		}

		// Create the popup dialog box
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Your costituency stats");
		dialogBox.setAnimationEnabled(true);
		final Button closeButton = new Button("Close");
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		final Label textToServerLabel = new Label();
		final HTML serverResponseLabel = new HTML();
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
		dialogVPanel.add(textToServerLabel);
		dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);

		// Create a handler for the sendButton and nameField
		class StateHandler implements ChangeHandler {
			private void populateStates() {
				greetingService.listStates(
					new AsyncCallback<SortedSet<String>>() {
						public void onFailure(Throwable caught) {
						}

						public void onSuccess(SortedSet<String> result) {
							state.addItem("...SELECT STATE...");
							for (String name : result) {
								state.addItem(name);
							}
						}
					});
			}
			
			private void populateConstituencies(String state) {
				greetingService.listConstituencies(state, 
					new AsyncCallback<List<String>>() {
						public void onFailure(Throwable caught) {
							DialogBox box = new DialogBox();
							box.setText(caught.getMessage());
						}

						public void onSuccess(List<String> result) {
							constituency.clear();
							constituency.addItem("...SELECT CONSTITUENCY...");
							for (String name : result) {
								constituency.addItem(name);
							}
						}
					});
			}
	
			@Override
			public void onChange(ChangeEvent event) {
				populateConstituencies(state.getItemText(state.getSelectedIndex()));
			}
		}
		
		// Create a handler for the sendButton and nameField
		class ConstituencyHandler implements ChangeHandler {
			private void populateMpDetails( String constituency, String state) {
				greetingService.getMpDetails(constituency, state,
					new AsyncCallback<Member>() {
						public void onFailure(Throwable caught) {
							DialogBox box = new DialogBox();
							box.setText(caught.getMessage());
						}
						
						private void setContainerText(String text, String containerId) {
							RootPanel container = RootPanel.get(containerId);
							container.clear();
							String multiLineText = text.replace(",", ",<br>");
							HTML html = new HTML(multiLineText.isEmpty() ? "Not Available" : multiLineText, true);
							container.add(html);
						}

						public void onSuccess(Member result) {
							RootPanel.get("mpDetailsContainer").setVisible(true);
							RootPanel.get("chartContainer").setVisible(false);
							RootPanel imgCont = RootPanel.get("mpImageContainer");
							imgCont.clear();
							Image img = new Image();
							img.setUrl(result.imageUrl);
							img.setHeight("100px");
							imgCont.add(img);
							setContainerText(result.firstName + " " + result.lastName, "mpNameContainer");
							setContainerText(result.partyName, "mpPartyContainer");
							setContainerText(result.telephoneNos, "mpPhoneContainer");
							setContainerText(result.emailIds, "mpEmailContainer");
							setContainerText(result.permanentAddress, "mpAddressContainer");
						}
					});
			}
	
			@Override
			public void onChange(ChangeEvent event) {
				populateMpDetails(constituency.getItemText(constituency.getSelectedIndex()),
						          state.getItemText(state.getSelectedIndex()));
			}
		}


		// Add a handler to send the name to the server
		StateHandler handler = new StateHandler();
		handler.populateStates();
		state.addChangeHandler(handler);
		ConstituencyHandler cHandler = new ConstituencyHandler();
		constituency.addChangeHandler(cHandler);
	}
}
